package cn.bmyi.apiautotest.common;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 基于HttpURLConnection封装http请求
 * 
 * @author 毛建杰
 *
 */
public class HttpRequest
{
	/**
	 * 将InputStream转换为String
	 * 
	 * @param inputStream
	 *            InputStream
	 * @return String
	 */
	public static String convertInputStreamToString(InputStream inputStream)
	{
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String line = null;
		try
		{
			while ((line = reader.readLine()) != null)
			{
				sb.append(line);
			}
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
		}
		return sb.toString();
	}

	/**
	 * 实现http请求调用
	 * 
	 * @param url
	 *            url
	 * @param method
	 *            http方法，包括GET、POST、PUT、DELETE等
	 * @param params
	 *            url参数
	 * @param headers
	 *            http header
	 * @param body
	 *            http body
	 * @return 服务器返回数据。如果程序出错，返回null；如果服务器报错，返回错误信息。
	 */
	public static String send(String url, String method, HashMap<String, String> params,
			HashMap<String, String> headers, Object body)
	{
		// 拼接url
		if (params != null)
		{
			StringBuilder sb = new StringBuilder();
			for (String key : params.keySet())
			{
				String param = params.get(key);
				if (param != null)
				{
					try
					{
						if (sb.toString().isEmpty())
						{
							sb.append("?");
							sb.append(URLEncoder.encode(key, "UTF-8"));
							sb.append("=");
							sb.append(URLEncoder.encode(param, "UTF-8"));
						}
						else
						{
							sb.append("&");
							sb.append(URLEncoder.encode(key, "UTF-8"));
							sb.append("=");
							sb.append(URLEncoder.encode(param, "UTF-8"));
						}
					}
					catch (UnsupportedEncodingException e)
					{
						Logger.error(e.getMessage());
						return null;
					}
				}
			}
			url = url + sb;
		}

		// 创建Http连接connection
		HttpURLConnection connection;
		try
		{
			connection = (HttpURLConnection) (new URL(url)).openConnection();
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return null;
		}

		// 设置method
		try
		{
			connection.setRequestMethod(method);
		}
		catch (ProtocolException e)
		{
			Logger.error(e.getMessage());
			return null;
		}

		// 设置headers
		if (headers != null)
		{
			for (String key : headers.keySet())
			{
				String value = headers.get(key);
				connection.setRequestProperty(key, value);
			}
		}

		// 设置body
		try
		{
			if (method.equals("GET"))
			{

			}
			else
			{
				// 设置允许向服务器写数据
				connection.setDoOutput(true);
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());

				// 将body写入out
				if (body != null)
				{
					out.write(body.toString().getBytes("UTF-8"));
				}
				else
				{
					out.write("".getBytes("UTF-8"));
				}
				out.flush();
				out.close();
			}
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return null;
		}

		// 设置连接超时和读数据超时时间
		connection.setConnectTimeout(Config.timeout * 1000);
		connection.setReadTimeout(Config.timeout * 1000);

		// 发送http请求并返回InputStream
		InputStream inputStream;
		try
		{
			inputStream = connection.getInputStream();
		}
		catch (IOException e)
		{
			return e.getMessage();
		}
		
		//InputStream转换为String，并返回
		return convertInputStreamToString(inputStream);
	}
}
